'use strict';
class perjs {
    constructor() {
        perjs.testTxt = {
            tel(txt) { return /^((0\d{2,3}-\d{7,8})|(1[35847]\d{9}))$/.test(txt); },
        };
        window.ajaxBefore = {};
        window.ajaxAfter = {};
        const structure = [Array, HTMLCollection, HTMLElement,];
        const face2document = ['cla'];
        const face2Window = [
            'random', 'isArray', 'toArray', 'ajax', 'testTxt', 'getCookie', 'setCookie', 'delCookie', 'events', 'copy', 'getLocalStorage', 'setLocalStorage', 'delLocalStorage',
            'extend'
        ];
        const face2Structure = [
            'indexOf', 'toArray', 'each', 'elim', 'css', 'show', 'hide', 'cla', 'hasCla', 'addCla', 'removeCla', 'toggleCla',
            'setAttr', 'getAttr', 'removeAttr', 'events', 'touchOneFinger', 'touchTwoFinger', 'handleClick', 'shuffle','click'
        ];
        face2Window.forEach(key => { window[key] = this[key] });
        face2document.forEach(key => { document[key] = this[key] });
        structure.forEach(key => { face2Structure.forEach(keys => { key.prototype[keys] = this[keys]; }); });
    };
    static _judgingEquipmentType() {
        const ua = window.navigator.userAgent;
        return {
            isPc: !/(?:Android|iPhone|SymbianOS|Windows Phone|iPad|iPod)/gi.test(ua),
            isIos: /(?:iphone|ipad|ipod)/gi.test(ua),
            isAndroid: /(?:android)/gi.test(ua),
            isWeChat: /(?:micromessenger)/gi.test(ua),
            isQB: /(?:MQQBrowser|QQ)/.test(ua),
            isWindowsPhone: /(?:Windows Phone)/.test(ua),
            isFireFox: /(?:Firefox)/.test(ua),
            isChrome: /(?:Chrome|CriOS)/.test(ua),
            isIpad: /(?:iPad|PlayBook)/.test(ua),
            isSafari: /(?:Safari)/.test(ua),
            isUC: /(?:UCWEB|UCBrowser)/.test(ua),
        };
    };
    static _handleMethod(key) {
        key.removeEvent = function(name) {
            if(!name) {
                for(var i in this.eventsHandle) {
                    const handle = this.eventsHandle[i];
                    window.removeEventListener? this.removeEventListener(handle.event , handle.fn): this.detachEvent('on' + handle.event , handle.fn);
                    delete this.eventsHandle[i];
                };
            } else {
                toArray(name).forEach(name => {
                    for(var i in this.eventsHandle) {
                        const handle = this.eventsHandle[i];
                        if(handle.event == name || handle.name == name || i == name) {
                            window.removeEventListener? this.removeEventListener(handle.event , handle.fn): this.detachEvent('on' + handle.event , handle.fn);
                            delete this.eventsHandle[i];
                        };
                    };
                });
            };
            return this;
        };
        key.emit = function(name, arg) {
            if(name) {
                toArray(name).forEach(name => {
                    for(var i in this.eventsHandle) {
                        if(this.eventsHandle[i].event == name || this.eventsHandle[i].name == name || i == name) {
                            this.eventsHandle[i].fn.call(this, window.event, arg, this.eventsArg);
                            this['on' + name] && this['on' + name]();
                        };
                    };
                });
            };
            return this;
        };
    };
    random(a = 0, b) {
        b == void 0&& ([a, b] = [0, a]);
        if(a == b) return this.random(a);
        if(a > b) [a, b] = [b, a];
        return Math.floor(Math.random() * (b - a + 1 ) + a);
    };
    indexOf(e, i=0) {
        for(; i < this.length; i++) if(this[i] == e) return i
        return -1;
    };
    extend(a, b) {
        for (const i in b) a[i] = b[i];
        return a;
    };
    isArray(obj) {
        if(/Array/i.test(Object.prototype.toString.call(obj)) || obj.namedItem || obj.forEach) return !0;
        return !1;
    };
    toArray() {
        if(arguments.length == 0 && this == void 0) return [];
        const array = this != void 0? toArray(this): [];
        for (const i of arguments) {
            if(isArray(i)) array.push(...toArray(...i));
            else array.push(i);
        };
        return array;
    };
    each(callback, setIndex) {
        const backData = [];
        toArray(this).forEach((key, index) => {
            if(setIndex) key.index = index;
            backData.push(callback.call(key, key, index));
        });
        return backData;
    };
    elim(e) {
        const _this = toArray(this);
        for(let i = 0; i < _this.length; i++) if(_this[i] == void 0 || _this[i] == null || _this[i] == NaN || _this[i] == e) _this.splice(i-- , 1);
        return _this;
    };
    shuffle() {
        for (let i = 0; i < this.length; i++) {
            const randomIndex = Math.round(Math.random() * (this.length - 1 - i)) + i;
            [this[i], this[randomIndex]] = [this[randomIndex], this[i]]
        };
        return this;
    };
    css(s) {
        if(s == void 0) {this.each(key => { key.style.cssText = ''; }); return this;}
        return this.each(key => { for(let i in s) key.style[i] = s[i]; }), this;
    };
    show() {
        return this.css({display: 'block'}), this;
    };
    hide() {
        return this.css({display: 'none'}), this;
    };
    ajax(params) {
        for (const i in ajaxBefore) ajaxBefore[i](params);
        let {url, data, open = 'POST', header, error, fn} = params;
        if(typeof data == 'object') data = win.qsToString(data);
        const ajax = new XMLHttpRequest();
        ajax.onreadystatechange = function () {
            if(this.readyState == 4) {
                for (const i in ajaxAfter) ajaxAfter[i](this, params);
                if(this.status===200) fn && fn.call(this, JSON.parse(this.responseText), this);
                else error && error.call(this, this.status, this);
            };
        };
        if(open == 'GET') {
            ajax.open(open, `${url}?${data}`,true);
            ajax.send();
        } else {
            ajax.open(open, url, true)
            if(!!header) ajax.setRequestHeader(header[0], header[1]);
            else ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            ajax.send(data);
        };
    };
    testTxt(txt, format) {
        if(format in perjs.testTxt) return perjs.testTxt[format](txt);
        return txt;
    };
    cla(className) {
        if(this.getElementsByClassName) return this.getElementsByClassName(className);
        return this.getElementsByTagName('*').each(key => { if(key.hasCla(className)) return key; }).elim();
    };
    hasCla(className) {
        return !!this.className.match(new RegExp('(^|\\s)' + className + '(\\s|$)'));
    };
    addCla(className) {
        this.each(key => { !key.hasCla (className) && (key.className += ' ' + className); });
    };
    removeCla(className) {
        if(className == void 0) {
            this.each(key => { key.className = ''; });
        } else {
            toArray(className).forEach(className => {
                this.each(key => {
                    if ( key.hasCla(className) ) key.className = key.className.replace(new RegExp('\\b' + className + '\\b', 'g'), '').replace( /(^\s*|\s*$)/g , '' );
                });
            });
        };
        return this;
    };
    toggleCla(className) {
        this.each(key => { key.hasCla(className) ? key.removeCla(className) : key.addCla(className); });
        return this;
    };
    setAttr(at) {
        this.each(key => { for(let i in at) key.setAttribute(i, at[i]); });
        return this;
    };
    getAttr(at) {
        return this.getAttribute(at);
    };
    removeAttr(at, ignore) {
        ignore = toArray(['src' , 'href' , 'id' , 'class'], ignore);
        if(at == void 0 || at == '') {
            this.each(key => { toArray(key.attributes).forEach(keys => { if(ignore.indexOf(keys.name) < 0) key.removeAttribute(keys.name); }); });
        } else {
            this.each(key => { toArray(at).forEach(keys => { key.removeAttribute(keys); }); });
        };
        return this;
    };
    getCookie(name) {
        if ( document.cookie.length <= 0 ) return null;
        let start = document.cookie.indexOf( name + "=" );
        let end = document.cookie.indexOf( ";" , start );
        if( start < 0 ) return null;
        if ( end < 0 ) end = document.cookie.length;
        start += name.length + 1;
        return unescape(document.cookie.substring(start , end));
    };
    setCookie(name, value, time) {
        time = time || function () {
            const d = new Date();
            d.setHours(new Date().getHours() + 1);
            return d;
        }();
        return document.cookie = `${name}=${escape(value)};expires=${time.toUTCString()}`;
    };
    delCookie(name) {
        return document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;'
    };
    getLocalStorage(name) {
        return window.localStorage.getItem(name);
    };
    setLocalStorage(name, value) {
        window.localStorage.setItem(name, value);
        return window.localStorage.getItem(name);
    };
    delLocalStorage(name) {
        window.localStorage.removeItem(name);
        return window.localStorage;
    };
    events (ev, arg) {
        let _this = this;
        if(_this == window) _this = [window];
        if(typeof ev == 'string') {
            const a = {};
            a[ev] = {event: ev, name: ev, fn: arg};
            ev = a;
        };
        _this.eventsArg = arg;
        _this.each(key => {
            for(let i in ev) {
                key.eventsArg = _this.eventsArg;
                key.eventsHandle = {...key.eventsHandle};
                key.eventsHandle[i] = { event: ev[i].event || i, name: ev[i].name || i, fn: ev[i].fn || ev[i] };
                perjs._handleMethod(key);
                window.addEventListener? key.addEventListener((key.eventsHandle[i].event || i), key.eventsHandle[i].fn): key.attachEvent('on' + (key.eventsHandle[i].event || i), key.eventsHandle[i].fn);
            };
        }, true);
        if(!_this.removeEvent) _this.removeEvent = name => { _this.each(key => { key.removeEvent(name); }); };
        if(!_this.emit) _this.emit = name => { _this.each(key => { key.emit(name); }); };
        return this;
    };
    click(fn, arg) {
        this.events({ event: 'click', fn }, arg);
    };
    touchOneFinger(event={}) {
        const defualtSatrt = function(e) {
            this.events({ touchmove: defualtMove });
            this.touchEventStartPosX = e.changedTouches[0].pageX;
            this.touchEventStartPosY = e.changedTouches[0].pageY;
            event.start && event.start.call(this, this, e, e.changedTouches[0], e.changedTouches[0].pageX, e.changedTouches[0].pageY);
        };
        const defualtMove = function(e) {
            event.move && event.move.call(this, this, e, e.changedTouches[0], e.changedTouches[0].pageX, e.changedTouches[0].pageY);
        };
        const defualtEnd = function(e) {
            this.removeEvent({ touchmove: defualtMove });
            event.end && event.end.call(this, this, e, e.changedTouches[0], e.changedTouches[0].pageX, e.changedTouches[0].pageY, this.touchEventStartPosX > e.changedTouches[0].pageX, this.touchEventStartPosY > e.changedTouches[0].pageY);
        };
        this.events({ touchstart: defualtSatrt, touchend: defualtEnd });
        return this;
    };
    touchTwoFinger(event={}) {
        // ?
    };
    listenKeyboard(event={}) {
        if(perjs._judgingEquipmentType.isIos) {
            this.events({
                focus(e) {
                    event.up && event.up.call(this, e, this);
                    if(event.intoView) this.scrollIntoView();
                },
                blur(e) {
                    event.down && event.down.call(this, e, this);
                },
            });
        };
        if(perjs._judgingEquipmentType.isAndroid) {
            let originHeight = document.documentElement.clientHeight || document.body.clientHeight;
            window.events('resize', (e) => {
                const resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
                if (originHeight < resizeHeight) {
                    event.down && event.down.call(this, e, this);
                } else {
                    event.up && event.up.call(this, e, this);
                    if(event.intoView) this.scrollIntoView();
                };
                originHeight = resizeHeight;
            });
        };
        return this;
    };
    copy(data) {
        let {el, btn, event = 'click', success} = data;
        if(el.nodeType && el.nodeType != 1 || !isArray(el)) el = document.getElementById(el);
        if(btn.nodeType && btn.nodeType != 1 || !isArray(btn)) btn = document.getElementById(btn);
        const eq = perjs._judgingEquipmentType();
        const events = {};
        events[event] = e => {
            if(eq.isIos) {
                const range = document.createRange();
                range.selectNode(el[e.target.index]);
                window.getSelection().addRange(range);
                window.getSelection().removeAllRanges();
            } else {
                let input = document.getElementById('Use2CopyInput');
                if(!input) {
                    input = document.createElement('input');
                    document.body.appendChild(input);
                    input.style.cssText = 'position: fixed; top: 110%; left: 110%;';
                    input.id = 'Use2CopyInput';
                };
                input.value = el[e.target.index].innerHTML;
                input.select();
                document.execCommand("copy");
            };
            success && success(data, el, btn);
        };
        btn.events(events);
    };
}

class perJs extends perjs {
    constructor() {
        super();
        this.init();
    }
    init() {
        window.win = {
            link:  `file:///D:/page/projects/changle`,
            width: "innerWidth" in window ? window.innerWidth : document.documentElement.clientWidth,
            height: "innerHeight" in window ? window.innerHeight : document.documentElement.clientHeight,
            hashchange: {},
            scroll: {},
            resize: {
                init: () => {
                    win.height = "innerHeight" in window ? window.innerHeight : document.documentElement.clientHeight;
                    win.width = "innerWidth" in window ? window.innerWidth : document.documentElement.clientWidth;
                }
            },
            href() {
                return window.location.host + window.location.pathname;
            },
            // host() {
            //     return `http://${window.location.host}`
            // },
            pathname() {
                return window.location.pathname;
            },
            qs() {
                return window.location.search.replace(/^\?/ , '');
            },
            hash() {
                return window.location.hash.replace(/^#/, '');
            },
            st(y, x) {
                y != void 0 && window.scrollTo(x || 0, y);
                return document.body.scrollTop || document.documentElement.scrollTop;
            },
            reload(link) {
                link? ((link == 'back' || link < 0) ? window.history.back() : window.location = link) : window.location.reload();
            },
            qsToString (obj, str = '', char = '=', ass = '&') {
                Object.keys(obj).map((key) => { str += `${key}${char}${obj[key]}${ass}`; });
                return str.replace(new RegExp(('\\' + ass || '\&') + '$') , '');
            },
            qsToSubject(str, obj = {}, char = '=', ass = '&') {
                if (!str)
                    if(win.qs() != '') return win.qsToSubject(win.qs());
                    else return obj;
                for( var i = 0 , str = str.split(ass) , len = str.length ; i < len ; i++ )
                    obj[ str[ i ].split(char)[ 0 ] ] = str[ i ].split(char)[ 1 ];
                return obj;
            },
        };
        window.events({
            'defaultResize': {
                name: 'defoutResize',
                event: 'resize',
                fn: function () {
                    for ( var i in win.resize ) win.resize[ i ] && win.resize[ i ]( win.width , win.height );
                },
            },
            'defaultScroll': {
                name: 'defaultScroll',
                event: 'scroll',
                fn: function () {
                    for ( var i in win.scroll ) win.scroll[ i ] && win.scroll[ i ]( win.st() );
                },
            },
        });
    }
}

const PerJs = new perJs();
window.emit(['resize', 'scroll']);

var jwt = '';
